//String转document对象
function parseDom(arg) {　　
	var objElement = document.createElement("div");　　
	objElement.innerHTML = arg;　　
	return objElement.childNodes[0];
};
//遍历Dom数组,查找包含指定字符串值的Dom
function DomContains(arrDom, str) {
	for (i in arrDom) {
		if (arrDom[i].innerText == undefined) continue;
		if (arrDom[i].innerText.indexOf(str) > -1) {
			return arrDom[i];
		}
	}
	return undefined;
}
//正则表达式删除字符串首尾空格
function Trim(str) {
	return str.replace(/^\s*(.*?)\s*$/g, "$1");
}
//站点列表模版
var webinfotab = '<li class="mui-table-view-cell"><a class="mui-navigate"><h4>加载失败</h4><h6>Error!</h6></a></li>';
//添加已配置网站名到列表
function addWeblist(webinfo) {
	var weblisttab = parseDom(webinfotab);
	if (webinfo.web_name == "default") return;
	weblisttab.querySelector("a h4").innerHTML = webinfo.web_name;
	weblisttab.querySelector("a h6").innerHTML = webinfo.web_url;
	document.getElementById("weblist").appendChild(weblisttab);
}

var Webmarker;
//加载站点配置列表
function getWebmarker() {
	plus.io.resolveLocalFileSystemURL("/storage/emulated/0/EasyReader/webmarker.json", function(entry) {
		entry.file(function(file) {
			var fileReader = new plus.io.FileReader();
			fileReader.readAsText(file, "utf-8");
			fileReader.onloadend = function(evt) {
				getBookmarker();	//加载书签列表
				document.querySelector("#weblist li").remove();
				Webmarker = eval(evt.target.result)
				for (info in Webmarker) {
					addWeblist(Webmarker[info]);
				}
			}
		}, function(e) {
			mui.toast("操作失败：\r\n" + e.message);
		});
	}, function(e) {
		mui.toast("读取站点配置失败");
	});
}

//更新Webmarker配置列表
mui(".updateWebmark").on("tap", ".title", function() {
	updateWebmark();
});
//更新站点配置列表
function updateWebmark() {
	plus.nativeUI.showWaiting("获取站点配置列表");
	mui.ajax({
		url: "http://git.oschina.net/Antecer/EasyReader/raw/master/unpackage/release/EasyReader/webmarker.json",
		timeout: 5000,
		dataType: 'html',
		success: function(WebmarkerJSON) {
			Webmarker = eval(WebmarkerJSON);
			document.getElementById("weblist").innerHTML = "";
			for (info in Webmarker) {
				addWeblist(Webmarker[info]);
			}
			createFile("EasyReader/webmarker.json", JSON.stringify(Webmarker, null, "\t"));
			plus.nativeUI.closeWaiting();
			mui.toast("获取在线配置成功");
		},
		error: function(e) {
			plus.nativeUI.closeWaiting();
			mui.toast(e.message);
		}
	});
}
//书签列表模版
var bookinfotab = '<li class="mui-table-view-cell">\
<div class="mui-slider-right mui-disabled"><a class="mui-btn mui-btn-red">删除</a></div>\
<div class="mui-slider-handle">\
	<div class="T1 Horizontal">\
		<div class="M1 Horizontal"><h6>书名:</h6><h6>书签:</h6><h6>最新:</h6></div>\
		<div class="M2 Horizontal"><h4 class="书名"></h4><h6 class="书签"></h5><h6 class="最新"></h6></div>\
	</div>\
	<div class="T2 Horizontal">\
		<div class="M1 Horizontal"><h6>来源:</h6><h6>作者:</h6><h6>分类:</h6></div>\
		<div class="M2 Horizontal"><h6 class="来源"></h6><h6 class="作者"></h6><h6 class="分类"></h6></div>\
	</div>\
</div></li>';
//添加书签内容到页面
function setBookInfo(bookinfo) {
	var booklisttab = parseDom(bookinfotab);
	booklisttab.querySelector(".书名").innerHTML = bookinfo.title_name;
	booklisttab.querySelector(".书签").innerHTML = bookinfo.title_mark;
	booklisttab.querySelector(".最新").innerHTML = bookinfo.title_last;
	booklisttab.querySelector(".来源").innerHTML = bookinfo.web_name;
	booklisttab.querySelector(".作者").innerHTML = bookinfo.author;
	booklisttab.querySelector(".分类").innerHTML = bookinfo.classify;
	var checkBookInfo = DomContains(document.querySelectorAll("#booklist li"), bookinfo.title_name);
	if (checkBookInfo) {
		checkBookInfo.parentNode.replaceChild(booklisttab, checkBookInfo);
	} else {
		document.getElementById("booklist").appendChild(booklisttab);
	}
}
var Bookmarker = undefined;
//加载书签列表
function getBookmarker() {
	plus.io.resolveLocalFileSystemURL("/storage/emulated/0/EasyReader/bookmarker.json", function(entry) {
		entry.file(function(file) {
			var fileReader = new plus.io.FileReader();
			fileReader.readAsText(file, "utf-8");
			fileReader.onloadend = function(evt) {
				if((evt.target.result).toString() == "") return;	//若书签列表为空则返回
				document.querySelector("#booklist li").remove();
				Bookmarker = eval(evt.target.result)
				for (info in Bookmarker) {
					setBookInfo(Bookmarker[info]);
				}
				plus.nativeUI.showWaiting("更新书签列表...");
				getnewmarklist(Bookmarker, 0);
			}
		}, function(e) {
			mui.toast("操作失败：\r\n" + e.message);
		});
	}, function(e) {
		mui.toast("您的书架是空的");
	});
}

// 扩展API加载完毕后调用 
mui.plusReady(function() {
	getWebmarker();
});
//获取选定网站的URL
//function getsearchurl() {
//	var searchview = plus.webview.getWebviewById("searchbook");
//	if (searchview) {
//		weburl = searchview.getURL();
//		searchview.close();
//		addbookmark(weburl.replace("//m", "//www"));
//	}
//}
//打开选定网站
mui("#weblist").on("tap", "li", function() {
	var weburl = this.querySelector("h6").innerText;
	if (weburl.indexOf("http://") > -1) {
		plus.runtime.openURL(weburl);
//		mui.openWindow({
//			url: weburl,
//			id: "searchbook",
//		});
	}
});

//打开选定条目
mui("#booklist").on("tap", ".mui-table-view-cell", function() {
	var bookname = this.querySelector(".书名").innerText;
	var Bmarker, Wmarker;
	for (i in Bookmarker) {
		if (Bookmarker[i].title_name == bookname) {
			Bmarker = Bookmarker[i];
			break;
		}
	}
	for (i in Webmarker) {
		if (Webmarker[i].url_page == "") continue;
		if (RegExp(Webmarker[i].url_page).test(Bmarker.url_page)) {
			Wmarker = Webmarker[i];
			break;
		}
	}
	if (Bmarker && Wmarker) {
		mui.openWindow({
			url: "bookreader.html",
			id: "bookreader",
			extras: {
				Bmarker: Bmarker,
				Wmarker: Wmarker
			}
		});
	} else {
		mui.toast("找不到该书籍的配置");
	}
});
//删除选定条目
mui("#booklist").on('tap', '.mui-btn', function(event) {
	var li = this.parentNode.parentNode;
	var bookname = li.querySelector(".书名").innerText;
	mui.confirm(bookname, '确定要删除该书籍？', ['删除', '取消'], function(e) {
		if (e.index == 0) {
			delbookmark(bookname);
		} else {
			setTimeout(function() {
				mui.swipeoutClose(li);
			}, 0);
		}
	});
});

//绑定菜单栏点击事件
mui(".mui-bar-nav").on("tap", "a", function() {
	if (this.getAttribute("id") == "menu") { //开关侧滑菜单
		offCanvasWrapper.offCanvas("show");
	}
	if (this.getAttribute("id") == "title") { //更新书签列表
		plus.nativeUI.showWaiting("更新书签列表...");
		getnewmarklist(Bookmarker, 0);
	}
	if (this.getAttribute("id") == "scaner") { //通过二维码添加书籍
		mui.openWindow({
			url: "barcode_scan.html",
			id: "barcode_scan"
		});
	}
});

//从回调参数更新书签
window.addEventListener('setbookmarker', function(event) {
	//获得事件参数 event.detail 是传递过来的变量名
	if (typeof event.detail == "string") {
		addbookmark(event.detail);
	}
	if (typeof event.detail == "object") {
		setbookmark(event.detail);
		if (event.detail.title_last == "待更新") {
			plus.nativeUI.showWaiting("更新书签列表...");
			getnewmarklist(Bookmarker, 0);
		}
	}
});

//新建书签
function addbookmark(markpage) {
	if (markpage.indexOf("http://") == 0) {
		var webinfo = undefined;
		for (info in Webmarker) {
			if (Webmarker[info].url_page == "") continue;
			if (RegExp(Webmarker[info].url_page).test(markpage)) {
				webinfo = Webmarker[info];
				break;
			}
		}
		if (webinfo) {
			mui.toast("正在解析书签");
			getnowmarks(webinfo, markpage);
		} else {
			plus.nativeUI.closeWaiting();
		}
	}
}

//获取书签信息
function getnowmarks(webinfo, markpage) {
	plus.nativeUI.showWaiting();
	mui.ajax({
		url: markpage,
		timeout: 5000,
		dataType: 'html',
		success: function(response) {
			var BookCache = $("<code></code>").append($(response));
			var bookinfo = {
				"url_page": "未知", //书签阅读页面
				"url_last": "未知", //检查更新页面
				"title_name": "未知", //书名
				"title_mark": "未知", //书签
				"title_last": "未知", //最新
				"web_name": "未知", //来源
				"author": "未知", //作者
				"classify": "未知" //分类
			};
			bookinfo.url_page = markpage;
			if (webinfo.patch_content) {
				eval(webinfo.patch_content);
			}
			bookinfo.url_last = BookCache.find(webinfo.url_last).attr("href");
			bookinfo.url_last = getAbsolute(markpage, bookinfo.url_last);
			bookinfo.title_name = BookCache.find(webinfo.title_name).text();
			bookinfo.title_mark = BookCache.find(webinfo.title_mark).text();
			bookinfo.web_name = webinfo.web_name;
			if (!bookinfo.title_name) {
				mui.toast("内容解析失败！");
				plus.nativeUI.closeWaiting();
				return;
			}
			getnewmarks(webinfo, bookinfo);
		},
		error: function(result) {
			mui.toast("书签信息获取失败!");
			plus.nativeUI.closeWaiting();
		}
	});
}

//获取最新章节
function getnewmarks(webinfo, bookinfo) {
	mui.ajax({
		url: bookinfo.url_last,
		timeout: 5000,
		dataType: 'html',
		success: function(indexcache) {
			var IndexCache = $("<code></code>").append($(indexcache));
			if (webinfo.patch_update != "") {
				eval(webinfo.patch_update);
			}
			bookinfo.title_last = IndexCache.find(webinfo.title_last).text();
			bookinfo.author = IndexCache.find(webinfo.author).text().replace(/.*作.*?者[：|:]/, "");
			bookinfo.classify = IndexCache.find(webinfo.classify).text().replace(/.*类.*?别[：|:]/, "").replace(/.*分.*?类[：|:]/, "");
			for (info in bookinfo) {
				bookinfo[info] = Trim(bookinfo[info]);
			}
			setbookmark(bookinfo);
			plus.nativeUI.closeWaiting();
		},
		error: function(e) {
			mui.toast("更新页获取失败!");
			plus.nativeUI.closeWaiting();
		}
	});
}

//新增或修改书签
function setbookmark(bookinfo) {
	if (!bookinfo.title_name) return;
	if (!bookinfo.title_last) return;
	for (info in Bookmarker) {
		if (Bookmarker[info].title_name == bookinfo.title_name) {
			Bookmarker[info] = bookinfo;
			break;
		}
		if (Bookmarker.length - info == 1) {
			Bookmarker.push(bookinfo);
		}
	}
	if(Bookmarker == undefined){	//若书签列表为空,新建书签列表
		document.querySelector("#booklist li").remove();
		Bookmarker = eval("[]");
		Bookmarker.push(bookinfo);
	}
	setBookInfo(bookinfo);
	savebookmark();
}
//删除书签
function delbookmark(delbookname) {
	for (i = 0; i < Bookmarker.length; i++) {
		if (Bookmarker[i].title_name == delbookname || Bookmarker[i].title_name == undefined) {
			Bookmarker.splice(i, 1); //删除指定数组对象
			--i;
		}
	}
	var checkBookInfo = DomContains(document.querySelectorAll("#booklist li"), delbookname);
	if (checkBookInfo) {
		checkBookInfo.remove();
	}
	mui.toast(delbookname + " 已删除!");
	savebookmark();
}
//保存书签列表
function savebookmark() {
	createFile("EasyReader/bookmarker.json", JSON.stringify(Bookmarker, null, "\t"));
}

//定义bookinfo结构格式
var defaultbookinfo = {
	"url_page": "未知",
	"url_last": "未知",
	"title_name": "未知",
	"title_mark": "未知",
	"title_last": "未知",
	"web_name": "未知",
	"author": "未知",
	"classify": "未知"
};

//相对路径转绝对路径
function getAbsolute(page, link) {
	webindex = page.replace(/(http....*?)\/.*/, "$1"); //当前页面的主目录
	thisparent = page.replace(/(.*\/).*$/, "$1"); //当前页面的父目录
	if (link.indexOf("http") == 0) return link;
	if (link.indexOf("/") == 0) return (webindex + link);
	return (thisparent + link);
}
//获取书签列表最新章节
var getnewmarklist = function gmlist(bookinfolist, listnum) {
	var webinfo = undefined;
	if (listnum == bookinfolist.length) {
		Bookmarker = bookinfolist;
		savebookmark();
		plus.nativeUI.closeWaiting();
		mui.toast("书签列表更新完成");
		return;
	}
	for (i in Webmarker) {
		if (Webmarker[i].url_page == "") continue;
		if (RegExp(Webmarker[i].url_page).test(bookinfolist[listnum].url_page)) {
			webinfo = Webmarker[i];
			break;
		}
	}
	mui.ajax({
		url: bookinfolist[listnum].url_last,
		timeout: 5000,
		dataType: 'html',
		success: function(indexcache) {
			var IndexCache = $("<code></code>").append($(indexcache));
			if (webinfo.patch_update) {
				eval(webinfo.patch_update);
			}
			bookinfolist[listnum].title_last = Trim(IndexCache.find(webinfo.title_last).text());
			bookinfolist[listnum].author = Trim(IndexCache.find(webinfo.author).text().replace(/.*作.*?者[：|:]/, ""));
			bookinfolist[listnum].classify = Trim(IndexCache.find(webinfo.classify).text().replace(/.*类.*?别[：|:]/, "").replace(/.*分.*?类[：|:]/, ""));
			setBookInfo(bookinfolist[listnum]);
			gmlist(bookinfolist, ++listnum);
		},
		error: function(e) {
			gmlist(bookinfolist, ++listnum);
		}
	});
}